package com.colabo.j2ee.web.oaf.security.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;

import com.colabo.j2ee.web.core.common.CommonConstants;
import com.colabo.j2ee.web.core.exception.ReadableMessage;
import com.colabo.j2ee.web.core.exception.ServiceException;
import com.colabo.j2ee.web.core.persistence.HqlWrapper;
import com.colabo.j2ee.web.core.pkgenerator.IPKGenerator;
import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;
import com.colabo.j2ee.web.core.util.PropertyUtil;
import com.colabo.j2ee.web.core.util.StringUtil;
import com.colabo.j2ee.web.core.vo.SessionUserHolder;
import com.colabo.j2ee.web.oaf.common.AppConstants;
import com.colabo.j2ee.web.oaf.monitorperspective.ILogDataService;
import com.colabo.j2ee.web.oaf.orgnization.model.IPPositionVO;
import com.colabo.j2ee.web.oaf.orgnization.model.IPRoleVO;
import com.colabo.j2ee.web.oaf.security.ISecurityStrategyGroupService;
import com.colabo.j2ee.web.oaf.security.ISecurityStrategyService;
import com.colabo.j2ee.web.oaf.security.model.IPArcSecurityStrategyVO;
import com.colabo.j2ee.web.oaf.security.model.IPStrategyGroupPrincipalVO;
import com.colabo.j2ee.web.oaf.security.model.IPStrategyGroupVO;
import com.colabo.j2ee.web.oaf.vo.IPAuditLogVO;

/**
 * 安全策略组业务操作Hibernate实现
 */
public class SecurityStrategyGroupServiceImpl extends DefaultServiceImpl implements ISecurityStrategyGroupService {
	// 类型为岗位
	private static final String POSITION_TYPE = "com.colabo.j2ee.web.oaf.orgnization.model.IPPositionVO";
	private static final String ROLE_TYPE = "com.colabo.j2ee.web.oaf.orgnization.model.IPRoleVO";
	private static final String SUPER_GROUP = "超级系统管理员组";

	// 可扩展按组配置
	private static final String CAN_STRATEGY_BYGROUP = "1";

	// 注入应用日志服务类
	private ILogDataService logDataService = null;

	// 注入系统安全策略服务类
	private ISecurityStrategyService securityStrategyService = null;

	public ISecurityStrategyService getSecurityStrategyService() {
		return securityStrategyService;
	}

	public void setSecurityStrategyService(ISecurityStrategyService securityStrategyService) {
		this.securityStrategyService = securityStrategyService;
	}

	public ILogDataService getLogDataService() {
		return logDataService;
	}

	public void setLogDataService(ILogDataService logDataService) {
		this.logDataService = logDataService;
	}
	
	protected class IPStrategyGroupMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			IPStrategyGroupVO item = new IPStrategyGroupVO();
			Object id = rs.getObject("GROUPKY");
			if(id!=null && !id.equals("") && !id.equals("null")){
				item.setId(id.toString());
			}else{
				item.setId(null);
			}
			
			Object svalue = rs.getObject("STRATEGY_VALUE");
			if(svalue!=null && !svalue.equals("") && !svalue.equals("null")){
				item.setStrategyValue(svalue.toString());
			}else{
				item.setStrategyValue(null);
			}
			
			Object sname = rs.getObject("STRATEGY_NAME");
			if(sname!=null && !sname.equals("") && !sname.equals("null")){
				item.setStrategyName(sname.toString());
			}else{
				item.setStrategyName(null);
			}
			
			Object gname = rs.getObject("GROUP_NAME");
			if(gname!=null && !gname.equals("") && !gname.equals("null")){
				item.setGroupName(gname.toString());
			}else{
				item.setGroupName(null);
			}
			
			Object mflag = rs.getObject("MODIFYFLAG");
			if(mflag!=null && !mflag.equals("") && !mflag.equals("null")){
				item.setModifyflag(mflag.toString());
			}else{
				item.setModifyflag(null);
			}
			
			Object isdefault = rs.getObject("ISDEFAULT");			
			if(isdefault!=null && !isdefault.equals("") && !isdefault.equals("null")){
				item.setIsdefault(isdefault.toString());
			}else{
				item.setIsdefault(null);
			}
			
			Object indexNo = rs.getObject("INDEX_NO");
			if(indexNo!=null && !indexNo.equals("") && !indexNo.equals("null")){
				item.setIndexNo(indexNo.toString());
			}else{
				item.setIndexNo(null);
			}
			
			Object bdesc = rs.getObject("BSTRATEGY_DESC");
			if(bdesc!=null && !bdesc.equals("") && !bdesc.equals("null")){
				item.setStrategyDesc(bdesc.toString());
			}else{
				item.setStrategyDesc(null);
			}
			
			Object cvale = rs.getObject("CSTRATEGY_VALUE");
			if(cvale!=null && !cvale.equals("") && !cvale.equals("null")){
				item.setSysStrategyValue(cvale.toString());
			}else{
				item.setSysStrategyValue(null);
			}
			
			Object ctime = rs.getObject("CREATEDTIME");
			if(ctime!=null && !ctime.equals("") && !ctime.equals("null")){
				item.setCreatedTimestamp(rs.getDate("CREATEDTIME"));
			}else{
				item.setCreatedTimestamp(null);
			}
			
			Object mid = rs.getObject("LASTMODIFIERID");
			if(mid!=null && !mid.equals("") && !mid.equals("null")){
				item.setLastModifierId(mid.toString());
			}else{
				item.setLastModifierId(null);
			}
			
			Object mtime = rs.getObject("LASTMODIFIEDTIME");
			if(mtime!=null && !mtime.equals("") && !mtime.equals("null")){
				item.setLastModifiedTimestamp(rs.getDate("LASTMODIFIEDTIME"));
			}else{
				item.setLastModifiedTimestamp(null);
			}
			
			Object delflag = rs.getObject("DELFLAG");
			if(delflag!=null && !delflag.equals("") && !delflag.equals("null")){
				item.setDelflag(delflag.toString());
			}else{
				item.setDelflag(null);
			}
			
			return item;
		}
	}

	/**
	 * 得到查询策略组名称分页列表（排除冗余信息）
	 * 
	 * @param aPageSize
	 *            每页记录数，从数据库中查出相应数量的记录
	 * @return 对象数组，有两个对象，第一个对象为查询记录的<code>List</code>集合对象，第二个为数据库中总记录数
	 * @throws ServiceException
	 */
	public Object[] initData(int aPageSize) throws ServiceException {
		String sql = "select distinct groupName,modifyflag,isdefault,indexNo from IPStrategyGroupVO";
		Object[] result = this.find_Hibernate_ComposedHQL(sql, null, null, null, 0, aPageSize, true, "indexNo", null, null);
		List list = this.findAll_Hibernate_ComposedHQL("select count(distinct groupName) from IPStrategyGroupVO");
		result[1] = (Long) list.get(0);
		return result;
	}

	/**
	 * 批量更新安全策略组数据
	 * 
	 * @param aObjectList
	 *            对象列表，有三个值，删除<code>bean</code>列表、更新<code>bean</code>的列表、新增<code>bean</code>的列表
	 * @return 整数对象数组，操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 * @throws ServiceException
	 */
	public Integer[] saveData(Map aObjectList) throws ServiceException {
		IPKGenerator keyService = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
		try {
			// 插入成功的记录数、更新成功的记录数、删除成功的记录数
			int insertCount = 0;
			int updateCount = 0;
			int deleteCount = 0;

			// 新增bean列表、更新bean的列表、删除bean的列表
			List insertBeanList = (ArrayList) aObjectList.get(CommonConstants.INSERT_BEAN_LIST);

			List updateBeanList = (ArrayList) aObjectList.get(CommonConstants.UPDATE_BEAN_LIST);

			List deleteBeanList = (ArrayList) aObjectList.get(CommonConstants.DELETE_BEAN_LIST);

			// 所有可扩展按组配置的系统安全策略列表
			List strategyList = getAllStrategies(CAN_STRATEGY_BYGROUP);
			// this.getHibernateTemplate().find("from IPArcSecurityStrategyVO
			// where extFlag='"+CAN_STRATEGY_BYGROUP+"'");

			IPStrategyGroupVO bean;
			SessionUserHolder user = (SessionUserHolder) getBean("sessionUserHolder");

			// 批量插入记录
			int insertListSize = insertBeanList.size();
			if (insertListSize > 0) {
				for (int i = 0; i < insertListSize; i++) {
					bean = (IPStrategyGroupVO) insertBeanList.get(i);
					// 判断是否存在重名
					String groupName = bean.getGroupName();
					if (checkGroupExistByName(groupName)) {
						throw new ServiceException(new ReadableMessage(AppConstants.MSG_ERR_APP_5003, new Object[] { groupName }));
					}

					// 对每个组名设置所有的安全策略
					for (int j = 0; j < strategyList.size(); j++) {
						IPStrategyGroupVO vo = new IPStrategyGroupVO();
						IPArcSecurityStrategyVO strategyVO = (IPArcSecurityStrategyVO) strategyList.get(j);
						vo.setId(keyService.getUUIDKey());
						vo.setGroupName(bean.getGroupName());
						vo.setModifyflag("1");
						vo.setIsdefault("0");
						// vo.setStrategyValue(strategyVO.getStrategyValue());
						vo.setStrategyName(strategyVO.getStrategyName());
						this.save_Hibernate_Object(vo);
					}

					// 插入应用日志
					logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_SYS_MAINTAIN, IPAuditLogVO.OP_CODE_SAVE, user.getStaffId(), user.getLoginIp(),
							PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_1009) + IPAuditLogVO.SEPARATE + groupName);
					insertCount++;
				}
			}

			// 批量更新记录
			int updateListSize = updateBeanList.size();
			if (updateListSize > 0) {
				for (int i = 0; i < updateListSize; i++) {
					bean = (IPStrategyGroupVO) updateBeanList.get(i);
					// 判断是否存在重名
					String groupName = bean.getGroupName();
					if (checkGroupExistByName(groupName)) {
						throw new ServiceException(new ReadableMessage(AppConstants.MSG_ERR_APP_5003, new Object[] { groupName }));
					}
					// 批量修改对应名称的所有安全策略组名称
					Object[] obj = { bean.getGroupName(), bean.getOldGroupName() };
					this.delete_Hibernate_ComposedQuery("UPDATE IP_STRATEGY_GROUP SET GROUP_NAME = ? " + "WHERE GROUP_NAME=?", obj);

					// 插入应用日志
					logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_SYS_MAINTAIN, IPAuditLogVO.OP_CODE_UPDATE, user.getStaffId(), user.getLoginIp(),
							PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_1009) + IPAuditLogVO.SEPARATE + groupName);

					updateCount++;
				}
			}

			// 批量删除记录
			int deleteListSize = deleteBeanList.size();
			if (deleteListSize > 0) {
				for (int i = 0; i < deleteListSize; i++) {
					bean = (IPStrategyGroupVO) deleteBeanList.get(i);
					Object[] obj = new Object[1];
					obj[0] = bean.getGroupName();

					// 批量删除对应名称的所有安全策略组关联岗位
					this.delete_Hibernate_ComposedQuery("DELETE FROM IP_STRATEGY_GROUP_PRINCIPAL "
							+ "WHERE GROUPKY IN (SELECT GROUPKY FROM IP_STRATEGY_GROUP WHERE GROUP_NAME=?)", obj);

					// 批量删除对应名称的所有安全策略组
					this.delete_Hibernate_ComposedQuery("DELETE FROM IP_STRATEGY_GROUP WHERE GROUP_NAME=?", obj);

					logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_SYS_MAINTAIN, IPAuditLogVO.OP_CODE_DELETE, user.getStaffId(), user.getLoginIp(),
							PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_1009) + IPAuditLogVO.SEPARATE + obj[0]);

					deleteCount++;
				}
			}

			return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };

		} catch (DataAccessException dae) {
			ReadableMessage msg = new ReadableMessage(AppConstants.MSG_ERR_APP_0005);
			throw new ServiceException(msg, dae);
		}
	}

	/**
	 * 根据参数获取系统安全策略值
	 * 
	 * @param extFlag
	 *            1：策略组中可配置，0：只有系统可配置
	 * @return
	 * @throws ServiceException
	 */
	public List getAllStrategies(String extFlag) throws ServiceException {
		return securityStrategyService.getAllStrategies(extFlag);
	}
	
	/**
	 * 根据策略名称得到策略值
	 * 
	 * @param strategyName
	 * @return 策略值
	 */
	public String getStrategyValue(String strategyName) {
		return securityStrategyService.getStrategyValue(strategyName);
	}

	/**
	 * 
	 * @param functionCode
	 * @return
	 * @throws ServiceException
	 */
	private boolean checkGroupExistByName(String groupName) throws ServiceException {
		// 筛选参数,将空参数除去
		HqlWrapper wrapper = new HqlWrapper();
		wrapper.setCondition("groupName", HqlWrapper.EQUAL, groupName);

		String[] propertyNames = StringUtil.listToStrArray(wrapper.getPropertyNames());
		String[] operators = StringUtil.listToStrArray(wrapper.getOperators());

		List valuesList = wrapper.getValues();
		Object[] values = valuesList == null || valuesList.size() == 0 ? null : valuesList.toArray();

		Object[] result = this.find_Hibernate_ComposedHQL("from IPStrategyGroupVO", propertyNames, operators, values, 0, -1, true, null, null, null);
		int count = ((Integer) result[1]).intValue();
		if (count > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 批量更新安全策略组明细数据
	 * 
	 * @param aObjectList
	 *            对象列表，有三个值，删除<code>bean</code>列表、更新<code>bean</code>的列表、新增<code>bean</code>的列表
	 * @return 整数对象数组，操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 * @throws ServiceException
	 */
	public Integer[] saveDetailData(Map aObjectList) throws ServiceException {
		IPKGenerator keyService = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
		try {
			// 插入成功的记录数、更新成功的记录数、删除成功的记录数
			int insertCount = 0;
			int updateCount = 0;
			int deleteCount = 0;

			// 新增bean列表、更新bean的列表、删除bean的列表
			List insertBeanList = (ArrayList) aObjectList.get(CommonConstants.INSERT_BEAN_LIST);
			List updateBeanList = (ArrayList) aObjectList.get(CommonConstants.UPDATE_BEAN_LIST);
			List deleteBeanList = (ArrayList) aObjectList.get(CommonConstants.DELETE_BEAN_LIST);

			IPStrategyGroupVO bean;

			// 批量插入记录
			int insertListSize = insertBeanList.size();
			if (insertListSize > 0) {
				for (int i = 0; i < insertListSize; i++) {
					bean = (IPStrategyGroupVO) insertBeanList.get(i);
					bean.setId(keyService.getUUIDKey());
					this.save_Hibernate_Object(bean);
					insertCount++;
				}
			}

			// 批量修改记录
			int updateListSize = updateBeanList.size();
			if (updateListSize > 0) {
				for (int i = 0; i < updateListSize; i++) {
					bean = (IPStrategyGroupVO) updateBeanList.get(i);
					String strategyValue = bean.getStrategyValue();
					// 如果组配置值为空，则自动赋予系统配置值
					if (strategyValue == null || strategyValue.equals("")) {
						bean.setStrategyValue(bean.getSysStrategyValue());
					}

					this.update_Hibernate_Object(bean);
					updateCount++;
				}
			}

			// 批量删除记录
			int deleteListSize = deleteBeanList.size();
			if (deleteListSize > 0) {
				for (int i = 0; i < deleteListSize; i++) {
					bean = (IPStrategyGroupVO) deleteBeanList.get(i);
					Object[] obj = { bean.getId() };

					// 批量删除安全策略组关联岗位
					this.delete_Hibernate_ComposedQuery("DELETE FROM IP_STRATEGY_GROUP_PRINCIPAL " + "WHERE GROUPKY=?", obj);

					// 删除安全策略组
					this.delete_Hibernate_Object(bean);
					deleteCount++;
				}
			}

			return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
		} catch (DataAccessException dae) {
			ReadableMessage msg = new ReadableMessage(AppConstants.MSG_ERR_APP_0005);
			throw new ServiceException(msg, dae);
		}
	}

	/**
	 * 批量更新安全策略组关联岗位数据
	 * 
	 * @param aObjectList
	 *            对象列表，有三个值，删除<code>bean</code>列表、更新<code>bean</code>的列表、新增<code>bean</code>的列表
	 * @param groupname
	 *            策略组名称
	 * @return 整数对象数组，操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 * @throws ServiceException
	 */
	public Integer[] savePosiData(Map aObjectList, String groupname) throws ServiceException {
		IPKGenerator keyService = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
		try {
			// 插入成功的记录数、更新成功的记录数、删除成功的记录数
			int insertCount = 0;
			int updateCount = 0;
			int deleteCount = 0;

			// 新增bean列表、更新bean的列表、删除bean的列表
			List insertBeanList = (ArrayList) aObjectList.get(CommonConstants.INSERT_BEAN_LIST);
			List updateBeanList = (ArrayList) aObjectList.get(CommonConstants.UPDATE_BEAN_LIST);
			List deleteBeanList = (ArrayList) aObjectList.get(CommonConstants.DELETE_BEAN_LIST);

			// 所有系统安全策略列表
			List groupList = this.getHibernateTemplate().find("from IPStrategyGroupVO where groupName='" + groupname + "'");
			int size = groupList.size();
			// 批量插入记录
			int insertListSize = insertBeanList == null ? 0 : insertBeanList.size();
			if (insertListSize > 0) {
				for (int j = 0; j < size; j++) {
					IPStrategyGroupVO group = (IPStrategyGroupVO) groupList.get(j);
					String groupid = group.getId();
					for (int i = 0; i < insertListSize; i++) {
						IPPositionVO posiVo = (IPPositionVO) insertBeanList.get(i);
						String positionid = posiVo.getPositionid();

						IPStrategyGroupPrincipalVO vo = new IPStrategyGroupPrincipalVO();
						vo.setGrantKy(keyService.getUUIDKey());
						vo.setGroupKy(groupid);
						vo.setPrincipalCode(positionid);
						vo.setPrincipalType(POSITION_TYPE);
						this.save_Hibernate_Object(vo);
					}
					insertCount++;
				}
			}

			// 批量修改记录
			int updateListSize = updateBeanList == null ? 0 : updateBeanList.size();
			if (updateListSize > 0) {

			}

			// 批量删除记录
			int deleteListSize = deleteBeanList == null ? 0 : deleteBeanList.size();
			if (deleteListSize > 0) {
				for (int i = 0; i < deleteListSize; i++) {
					IPPositionVO posiVo = (IPPositionVO) deleteBeanList.get(i);
					Object[] obj = { posiVo.getPositionid(), POSITION_TYPE, groupname };

					StringBuffer sql = new StringBuffer("DELETE FROM IP_STRATEGY_GROUP_PRINCIPAL ");
					sql.append("WHERE PRINCIPAL_CODE=? AND PRINCIPAL_TYPE=? AND GROUPKY ").append(
							"IN(SELECT GROUPKY FROM IP_STRATEGY_GROUP WHERE GROUP_NAME=?)");

					this.delete_Hibernate_ComposedQuery(sql.toString(), obj);
					// bean = (IPStrategyGroupVO) updateBeanList.get(i);
					// this.delete_Hibernate_Object(bean);
					deleteCount++;
				}
			}

			return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };

		} catch (DataAccessException dae) {
			ReadableMessage msg = new ReadableMessage(AppConstants.MSG_ERR_APP_0005);
			throw new ServiceException(msg, dae);
		}
	}

	/**
	 * 批量更新安全策略组关联角色数据
	 * 
	 * @param aObjectList
	 *            对象列表，有三个值，删除<code>bean</code>列表、更新<code>bean</code>的列表、新增<code>bean</code>的列表
	 * @param groupname
	 *            策略组名称
	 * @return 整数对象数组，操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 * @throws ServiceException
	 */
	public Integer[] saveRoleData(Map aObjectList, String groupname) throws ServiceException {
		IPKGenerator keyService = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
		try {
			// 插入成功的记录数、更新成功的记录数、删除成功的记录数
			int insertCount = 0;
			int updateCount = 0;
			int deleteCount = 0;

			// 新增bean列表、更新bean的列表、删除bean的列表
			List insertBeanList = (ArrayList) aObjectList.get(CommonConstants.INSERT_BEAN_LIST);

			List updateBeanList = (ArrayList) aObjectList.get(CommonConstants.UPDATE_BEAN_LIST);

			List deleteBeanList = (ArrayList) aObjectList.get(CommonConstants.DELETE_BEAN_LIST);


			// 所有系统安全策略列表
			List groupList = this.getHibernateTemplate().find("from IPStrategyGroupVO where groupName='" + groupname + "'");
			int size = groupList.size();
			// 批量插入记录
			int insertListSize = insertBeanList == null ? 0 : insertBeanList.size();
			if (insertListSize > 0) {
				for (int j = 0; j < size; j++) {
					IPStrategyGroupVO group = (IPStrategyGroupVO) groupList.get(j);
					String groupid = group.getId();
					for (int i = 0; i < insertListSize; i++) {
						IPRoleVO roleVo = (IPRoleVO) insertBeanList.get(i);
						String roleid = roleVo.getRoleid();

						IPStrategyGroupPrincipalVO vo = new IPStrategyGroupPrincipalVO();
						vo.setGrantKy(keyService.getUUIDKey());
						vo.setGroupKy(groupid);
						vo.setPrincipalCode(roleid);
						vo.setPrincipalType(ROLE_TYPE);
						this.save_Hibernate_Object(vo);
					}
					insertCount++;
				}
			}

			// 批量修改记录
			int updateListSize = updateBeanList == null ? 0 : updateBeanList.size();
			if (updateListSize > 0) {

			}

			// 批量删除记录
			int deleteListSize = deleteBeanList == null ? 0 : deleteBeanList.size();
			if (deleteListSize > 0) {
				for (int i = 0; i < deleteListSize; i++) {
					IPRoleVO roleVo = (IPRoleVO) deleteBeanList.get(i);
					Object[] obj = { roleVo.getRoleid(), ROLE_TYPE, groupname };

					StringBuffer sql = new StringBuffer("DELETE FROM IP_STRATEGY_GROUP_PRINCIPAL ");
					sql.append("WHERE PRINCIPAL_CODE=? AND PRINCIPAL_TYPE=? AND GROUPKY ").append(
							"IN(SELECT GROUPKY FROM IP_STRATEGY_GROUP WHERE GROUP_NAME=?)");

					this.delete_Hibernate_ComposedQuery(sql.toString(), obj);
					// bean = (IPStrategyGroupVO) updateBeanList.get(i);
					// this.delete_Hibernate_Object(bean);
					deleteCount++;
				}
			}

			return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };

		} catch (DataAccessException dae) {
			ReadableMessage msg = new ReadableMessage(AppConstants.MSG_ERR_APP_0005);
			throw new ServiceException(msg, dae);
		}
	}

	/**
	 * 条件查询，根据传入的条件，进行数据查询，查询安全策略组名称
	 * 
	 * @param aParams
	 *            查询条件集合
	 * @param aOffset
	 *            记录开始位置
	 * @param aPageSize
	 *            查询记录条数
	 * @return 对象数组，有两个对象，第一个对象为查询记录的<code>List</code>集合对象，第二个为数据库中符合查询条件的总记录数
	 * @throws ServiceException
	 */
	public Object[] queryData(Map aParams, int aOffset, int aPageSize) throws ServiceException {
		// 用distinct排除冗余组名
		String sql = "select distinct groupName,modifyflag,isdefault,indexNo from IPStrategyGroupVO";

		// 筛选参数,将空参数除去
		HqlWrapper wrapper = new HqlWrapper();
		String groupName = (String) aParams.get("groupName");
		wrapper.setCondition("groupName", HqlWrapper.INCLUDE, groupName);

		String[] propertyNames = StringUtil.listToStrArray(wrapper.getPropertyNames());
		String[] operators = StringUtil.listToStrArray(wrapper.getOperators());

		List valuesList = wrapper.getValues();
		Object[] values = valuesList == null || valuesList.size() == 0 ? null : valuesList.toArray();
		String orderBy = "indexNo";
		String groupBy = null;
		String otherCause = null;

		Object[] result = this.find_Hibernate_ComposedHQL(sql, propertyNames, operators, values, aOffset, aPageSize, true, orderBy, groupBy,
				otherCause);

		// 由于分页查询中不能正确取出冗余数据的个数，所以在这里重新查询总数覆盖result[1]以达到效果
		StringBuffer sqlstr = new StringBuffer("select count(distinct groupName) from IPStrategyGroupVO");
		if (groupName != null && !groupName.equals("")) {
			sqlstr.append(" where groupName like '%").append(groupName).append("%'");
		}
		List list = this.findAll_Hibernate_ComposedHQL(sqlstr.toString());
		result[1] = (Long) list.get(0);

		return result;
	}

	/**
	 * 将所有安全策略查询出来汇总成一个对比表格
	 * @return 
	 * @throws ServiceException
	 */
	public List queryForStrategyMatrix() throws ServiceException {
		StringBuffer sqlstr = new StringBuffer("SELECT A.Strategy_Value ASTRATEGY_VALUE,B.STRATEGY_DESC BSTRATEGY_DESC, ")
			.append("(select C.STRATEGY_VALUE from IP_STRATEGY_GROUP C where A.STRATEGY_NAME=C.STRATEGY_NAME and C.GROUP_NAME ='超级系统管理员组' )CSTRATEGY_VALUE, ")
	       .append(" (select D.STRATEGY_VALUE from IP_STRATEGY_GROUP D where A.STRATEGY_NAME=D.STRATEGY_NAME and D.GROUP_NAME ='二级安全策略标准' )DSTRATEGY_VALUE, ")
	       .append(" (select E.STRATEGY_VALUE from IP_STRATEGY_GROUP E where A.STRATEGY_NAME=E.STRATEGY_NAME and E.GROUP_NAME ='三级安全策略标准' )ESTRATEGY_VALUE, ")
	       .append(" (select F.STRATEGY_VALUE from IP_STRATEGY_GROUP F where A.STRATEGY_NAME=F.STRATEGY_NAME and F.GROUP_NAME ='自定义安全策略' )FSTRATEGY_VALUE ")
	       .append(" FROM IP_ARCSECURITY_STRATEGY B,IP_STRATEGY_GROUP A")
	       .append(" WHERE A.STRATEGY_NAME=B.STRATEGY_NAME and A.GROUP_NAME ='一级安全策略标准'");
	       
		List result = getJdbcTemplate().queryForList(sqlstr.toString()); 
//		List result = getJdbcTemplate().query(sqlstr.toString(), new StrategyMatrixMapper());    
	    return result;
	}
	/**
	 * 条件查询，根据传入的条件，进行数据查询，查询安全策略组明细
	 * 
	 * @param aParams
	 *            查询条件集合
	 * @param aOffset
	 *            记录开始位置
	 * @param aPageSize
	 *            查询记录条数
	 * @return 对象数组，有两个对象，第一个对象为查询记录的<code>List</code>集合对象，第二个为数据库中符合查询条件的总记录数
	 * @throws ServiceException
	 */
	public Object[] queryDetailData(Map aParams, int aOffset) throws ServiceException {
		// 使用联合查询，查询出安全策略组明细及对应的策略描述信息
		StringBuffer sqlstr = new StringBuffer("SELECT A.*,B.STRATEGY_DESC AS BSTRATEGY_DESC,")
		.append("(select C.STRATEGY_VALUE from IP_STRATEGY_GROUP C where A.STRATEGY_NAME=C.STRATEGY_NAME and C.GROUP_NAME =? )CSTRATEGY_VALUE ")
		.append(" FROM IP_ARCSECURITY_STRATEGY B,IP_STRATEGY_GROUP A")
		.append(" WHERE A.STRATEGY_NAME=B.STRATEGY_NAME and A.GROUP_NAME =?");
		
		List paramlist = new ArrayList();
		List typelist = new ArrayList();
		

		String sysgroupName = (String) aParams.get("sysgroupName");
		if (sysgroupName != null) {
			paramlist.add(aParams.get("sysgroupName"));
			typelist.add(new Integer(Types.CHAR));
		}
		
		String groupName = (String) aParams.get("groupName");
		if (groupName != null) {
			paramlist.add(aParams.get("groupName"));
			typelist.add(new Integer(Types.CHAR));
		}
		Object[] result = new Object[2];
		Object[] params = paramlist.toArray();
		int[] types = new int[typelist.size()];
		for (int i = 0; i < typelist.size(); i++) {
			types[i] = Integer.parseInt(typelist.get(i).toString());
		}
		List list = getJdbcTemplate().query(sqlstr.toString(), params, types, new IPStrategyGroupMapper());
		result[0] = list;
		result[1] = new Integer(list.size());
		return result;
	}

	/**
	 * 条件查询，根据传入的条件，进行数据查询，查询安全策略组关联岗位
	 * 
	 * @param aParams
	 *            查询条件集合
	 * @param aOffset
	 *            记录开始位置
	 * @param aPageSize
	 *            查询记录条数
	 * @param type
	 *            查询的类型
	 * @return 对象数组，有两个对象，第一个对象为查询记录的<code>List</code>集合对象，第二个为数据库中符合查询条件的总记录数
	 * @throws ServiceException
	 */
	public Object[] queryPosiData(Map aParams, int aOffset, int aPageSize, String type) throws ServiceException {
		StringBuffer sql = null;
		// 如果对应类型为【岗位】，查询关联岗位
		if (POSITION_TYPE.equals(type)) {
			// 使用联合查询，查询出安全策略组关联岗位对应的岗位信息
			sql = createPosiQuerySQL(aParams, type);
		} else if (ROLE_TYPE.equals(type)) {
			// 使用联合查询，查询出安全策略组关联角色对应的角色信息
			sql = createRoleQuerySQL(aParams, type);
		}
		HqlWrapper wrapper = new HqlWrapper();
		String[] propertyNames = StringUtil.listToStrArray(wrapper.getPropertyNames());
		String[] operators = StringUtil.listToStrArray(wrapper.getOperators());

		List valuesList = wrapper.getValues();
		Object[] values = valuesList == null || valuesList.size() == 0 ? null : valuesList.toArray();
		String orderBy = null;
		String groupBy = null;
		String otherCause = null;
		Object[] result = this.find_Hibernate_ComposedHQL(sql.toString(), propertyNames,
				operators, values, aOffset, aPageSize, true, orderBy, groupBy,
				otherCause);
		
		//由于分页查询中不能正确取出冗余数据的个数，所以在这里重新查询总数覆盖result[1]以达到效果
		String sqlstr = sql.toString().replaceAll("select distinct b from", "select count(distinct b) from");
		List list = this.findAll_Hibernate_ComposedHQL(sqlstr);
		result[1] = (Long)list.get(0);

		return result;
	}

	private StringBuffer createPosiQuerySQL(Map aParams, String type) {
		StringBuffer sql = new StringBuffer("select distinct b from IPStrategyGroupPrincipalVO as a,IPPositionVO as b,IPStrategyGroupVO as c")
			.append(" where a.principalCode=b.positionid and a.groupKy=c.id");

		// 获取安全策略组主键信息，如果不为空，则加入对应查询条件
		String groupKy = (String) aParams.get("groupKy");
		if(groupKy!=null && !"null".equals(groupKy) &&!"".equals(groupKy)){

			sql.append(" and a.groupKy ='").append(groupKy).append("'");
		}
		
		String groupName = (String)aParams.get("groupName");
		if(groupName!=null && !"null".equals(groupName) &&!"".equals(groupName)){
			sql.append(" and c.groupName ='").append(groupName).append("'");
		}
		
		// 加入类型查询条件
		sql.append(" and a.principalType ='").append(type).append("'");
		return sql;
	}

	private StringBuffer createRoleQuerySQL(Map aParams, String type) {
		StringBuffer sql = new StringBuffer("select distinct b from IPStrategyGroupPrincipalVO as a,IPRoleVO as b,IPStrategyGroupVO as c")
			.append(" where a.principalCode=b.roleid and a.groupKy=c.id");

		// 获取安全策略组主键信息，如果不为空，则加入对应查询条件
		String groupKy = (String) aParams.get("groupKy");
		if (groupKy != null) {
			sql.append(" and a.groupKy ='").append(groupKy).append("'");
		}
		
		String groupName = (String)aParams.get("groupName");
		if(groupName!=null){
			sql.append(" and c.groupName ='").append(groupName).append("'");
		}
		
		// 加入类型查询条件
		sql.append(" and a.principalType ='").append(type).append("'");
		return sql;
	}

	/**
	 * 获取安全策略组下存在的对应岗位关系个数
	 * 
	 * @param groupName
	 *            策略组名称
	 * @return 存在对应岗位关系的个数
	 * @throws ServiceException
	 */
	public int isContainsPosi(String groupName) throws ServiceException {
		StringBuffer sql = new StringBuffer("select a from IPStrategyGroupPrincipalVO as a,IPStrategyGroupVO as b").append(" where a.groupKy=b.id");

		if (groupName != null) {
			sql.append(" and b.groupName ='").append(groupName).append("'");
		}

		Object[] result = this.find_Hibernate_ComposedHQL(sql.toString(), null, null, null, 0, -1, true, null, null, null);
		return ((Integer) result[1]).intValue();
	}

	/**
	 * 判断策略组下是否存在未配置策略值的项
	 * 
	 * @param groupName
	 * @return true：存在未配置策略值的项，false：不存在未配置策略值的项
	 * @throws ServiceException
	 */
	public boolean isHasStategyWithNoValue(String groupName) throws ServiceException {
		StringBuffer sql = new StringBuffer("select a from IPStrategyGroupVO as a where a.groupName = '").append(groupName).append("'").append(
				" and strategyValue is null");

		Object[] result = this.find_Hibernate_ComposedHQL(sql.toString(), null, null, null, 0, -1, true, null, null, null);

		int count = ((Integer) result[1]).intValue();
		if (count > 0) {
			return true;
		}

		return false;
	}

	/**
	 * 设置指定的组为默认
	 * 
	 * @param groupName
	 * @throws ServiceException
	 */
	public void setDefalutGroup(String groupName) throws ServiceException {
		// 批量修改对应名称的所有安全策略组名称
		Object[] obj0 = null;
		this.delete_Hibernate_ComposedQuery("UPDATE IP_STRATEGY_GROUP SET ISDEFAULT = '0' " + "WHERE ISDEFAULT = '1' and GROUP_NAME<>'"+SUPER_GROUP+"'", obj0);
		Object[] obj = { groupName };
		this.delete_Hibernate_ComposedQuery("UPDATE IP_STRATEGY_GROUP SET ISDEFAULT = '1' " + "WHERE GROUP_NAME=?", obj);
	}
}